package com.aaa.project.commdetail.service.impl;

import com.aaa.project.commdetail.domain.TempTimeStat;
import com.aaa.project.commdetail.mapper.TempTimeStatMapper;
import com.aaa.project.commdetail.service.TempTimeStatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author baibin
 * @version 1.0
 * @date 2025/4/22 23:27
 * @description TempTimeStatServiceImpl
 */
@Service
public class TempTimeStatServiceImpl implements TempTimeStatService {

    private static final Logger log = LoggerFactory.getLogger(TempTimeStatServiceImpl.class);

    @Resource
    private TempTimeStatMapper mapper;

    @Override
    public void add(TempTimeStat tempTimeStat) {
        log.info("TempTimeStatServiceImpl add params:{}", tempTimeStat);
        // 查询是否已经新增过记录
        TempTimeStat vo = mapper.get(tempTimeStat);
        if (vo == null) {
            mapper.insert(tempTimeStat);
        } else {
            // 比较online值 相等则不更新
            if (vo.getOnline().equals(tempTimeStat.getOnline())) {
                log.info("The online value has not changed. Skip the update.");
                return;
            }
            // online新值和旧值不相等 需要进行逐位比较合并
            String newOnline = tempTimeStat.getOnline();
            String oldOnline = vo.getOnline();
            StringBuilder mergedOnline = new StringBuilder();
            // 逐位比较并合并
            for (int i = 0; i < 96; i++) {
                char newChar = newOnline.charAt(i);
                char oldChar = oldOnline.charAt(i);
                // 如果旧值的某一位已经是1，则保留旧值
                if (oldChar == '1') {
                    mergedOnline.append(oldChar);
                } else {
                    // 否则，选择新值
                    mergedOnline.append(newChar);
                }
            }
            // 更新合并后的online值
            vo.setOnline(mergedOnline.toString());
            // 更新记录
            mapper.update(vo);
        }
    }
}
